package org.pylates;

import java.util.Map;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.python.core.PyObject;

public class PyTemplate extends StringTemplate {

	private boolean passErrorsAsResults = true;

	protected PyObject attachedFunction;

	public PyObject getAttachedFunction() {
		return attachedFunction;
	}

	public static StringTemplateGroup defaultPyGroup = new PyTemplateGroup("defaultPyGroup", ".");

	public PyTemplate() {
		super();
		setGroup(defaultPyGroup);
	}

	public PyTemplate(PyObject pyObject) {
		super();
		setGroup(defaultPyGroup);
		this.attachedFunction = pyObject;
	}

	public PythonFacade getPythonFacade() {
		PyTemplateGroup pyGroup = (PyTemplateGroup) this.group;
		PythonFacade facade = pyGroup.getPython();
		if (facade == null) {
			facade = ((PyTemplateGroup) defaultGroup).getPython();
		}
		return facade;
	}

	/**
	 * Duplicate itself for instance cloning
	 */
	@Override
	protected void dup(StringTemplate from, StringTemplate to) {
		super.dup(from, to);
		if (from instanceof PyTemplate && to instanceof PyTemplate) {
			((PyTemplate) to).attachedFunction = ((PyTemplate) from).attachedFunction;
		}
	}

	/**
	 * Primitive used to generate resulting Template value
	 * 
	 * @throws PyTemplateException
	 */
	protected String invoke() throws PyTemplateException {
		String result = getPythonFacade().invoke(this);
		if (result == null) {
			throw new PyTemplateException("Obtained null instead of string, while invoking PyTemplate");
		}
		return result;
	}
	
	/**
	 * Return template value as string
	 * 
	 * @return string
	 */
	@Override
	public String toString() {
		try {
			return invoke();
		} catch (PyTemplateException e) {
			error(e.toString());
			if (passErrorsAsResults) {
				return e.toString();
			}
		}
		return "";
	}
	
}
